<template>
  <div class="todo-list">
    <h2>待办事项</h2>
    
    <!-- 筛选器 -->
    <div class="filters">
      <button 
        v-for="filter in filters" 
        :key="filter.value"
        :class="{ active: currentFilter === filter.value }"
        @click="setFilter(filter.value)"
      >
        {{ filter.label }}
      </button>
    </div>
    
    <!-- 排序选项 -->
    <!-- 搜索框 -->
    <div class="search-box">
      <input 
        type="text" 
        v-model="searchQuery" 
        placeholder="搜索任务标题..." 
        class="search-input"
      >
      <button @click="clearSearch" class="clear-search" v-if="searchQuery">×</button>
    </div>
    
    <div class="sort-options">
      <label for="sort-by">排序方式:</label>
      <select id="sort-by" v-model="sortBy">
        <option value="dueDate">截止时间</option>
        <option value="priority">优先级</option>
        <option value="createdAt">创建时间</option>
      </select>
    </div>
    
    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedTodos.length > 0">
      <span>已选择 {{ selectedTodos.length }} 项</span>
      <button class="btn-batch-complete" @click="batchComplete">批量完成</button>
      <button class="btn-batch-delete" @click="batchDelete">批量删除</button>
      <button class="btn-batch-cancel" @click="cancelSelection">取消选择</button>
    </div>
    
    <!-- 待办事项列表 -->
    <ul 
      v-if="filteredTodos.length > 0" 
      class="todos-container"
      @drop="onDrop"
      @dragover.prevent
    >
      <li 
        v-for="todo in filteredTodos" 
        :key="todo._id"
        :class="['todo-item', { completed: todo.completed, selected: selectedTodos.includes(todo._id) }]"
        @click.shift.exact="toggleTodoSelection(todo._id)"
        draggable="true"
        @dragstart="onDragStart($event, todo._id)"
        @dragover.prevent="onDragOver($event, todo._id)"
      >
        <div class="todo-selection" @click="toggleTodoSelection(todo._id)">
          <input 
            type="checkbox" 
            :checked="selectedTodos.includes(todo._id)"
            @click.stop="toggleTodoSelection(todo._id)"
          >
        </div>
        <div class="todo-content">
          <div class="todo-title">{{ todo.title }}</div>
          <div class="todo-description" v-if="todo.description">{{ todo.description }}</div>
          <div class="todo-meta">
            <span class="todo-category">{{ getCategoryText(todo.category) }}</span>
            <span class="todo-priority">{{ getPriorityText(todo.priority) }}</span>
            <span class="todo-due-date" :class="{ 'high-priority': isHighPriorityNearDue(todo) }">
              {{ formatDueDate(todo.dueDate) }}
            </span>
          </div>
          <div class="todo-tags" v-if="todo.tags && todo.tags.length > 0">
            <span v-for="tag in todo.tags" :key="tag" class="tag">{{ tag }}</span>
          </div>
        </div>
        <div class="todo-actions">
          <button 
            :class="['btn-complete', { 'completed': todo.completed }]"
            @click="toggleComplete(todo._id)"
          >
            {{ todo.completed ? '取消完成' : '标记完成' }}
          </button>
          <button class="btn-edit" @click="editTodo(todo._id)">编辑</button>
          <button class="btn-delete" @click="deleteTodo(todo._id)">删除</button>
        </div>
      </li>
    </ul>
    
    <!-- 空状态 -->
    <div v-else class="empty-state">
      暂无待办事项
    </div>
  </div>
</template>

<script>
export default {
  name: 'TodoList',
  props: {
    todos: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      currentFilter: 'all',
      sortBy: 'dueDate',
      searchQuery: '',
      selectedTodos: [],
      dragTodoId: null,
      filters: [
        { label: '全部', value: 'all' },
        { label: '未完成', value: 'pending' },
        { label: '已完成', value: 'completed' },
        { label: '工作', value: 'work' },
        { label: '学习', value: 'study' },
        { label: '生活', value: 'life' }
      ]
    }
  },
  computed: {
    filteredTodos() {
      let filtered = [...this.todos];
      
      // 应用搜索过滤
      if (this.searchQuery) {
        filtered = filtered.filter(todo => 
          todo.title.toLowerCase().includes(this.searchQuery.toLowerCase())
        );
      }
      
      // 应用筛选器
      switch (this.currentFilter) {
        case 'pending':
          filtered = filtered.filter(todo => !todo.completed);
          break;
        case 'completed':
          filtered = filtered.filter(todo => todo.completed);
          break;
        case 'work':
        case 'study':
        case 'life':
          filtered = filtered.filter(todo => todo.category === this.currentFilter);
          break;
      }
      
      // 应用排序
      filtered.sort((a, b) => {
        switch (this.sortBy) {
          case 'dueDate':
            // 未设置截止时间的排在最后
            if (!a.dueDate && !b.dueDate) return 0;
            if (!a.dueDate) return 1;
            if (!b.dueDate) return -1;
            return new Date(a.dueDate) - new Date(b.dueDate);
          case 'priority':
            // 高优先级排在前面
            const priorityOrder = { 'high': 3, 'medium': 2, 'low': 1 };
            return priorityOrder[b.priority] - priorityOrder[a.priority];
          case 'createdAt':
            // 按创建时间倒序排列
            return new Date(b.createdAt) - new Date(a.createdAt);
          default:
            return 0;
        }
      });
      
      return filtered;
    }
  },
  methods: {
    setFilter(filter) {
      this.currentFilter = filter;
    },
    toggleComplete(id) {
      this.$emit('toggle-complete', id);
    },
    editTodo(id) {
      const todo = this.todos.find(t => t._id === id);
      if (todo) {
        this.$emit('edit-todo', todo);
      }
    },
    deleteTodo(id) {
      this.$emit('delete-todo', id);
    },
    getCategoryText(category) {
      const categories = {
        'work': '工作',
        'study': '学习',
        'life': '生活'
      };
      return categories[category] || category;
    },
    getPriorityText(priority) {
      const priorities = {
        'high': '高优先级',
        'medium': '中优先级',
        'low': '低优先级'
      };
      return priorities[priority] || priority;
    },
    formatDueDate(dueDate) {
      if (!dueDate) return '无截止时间';
      return new Date(dueDate).toLocaleString('zh-CN');
    },
    isHighPriorityNearDue(todo) {
      return todo.priority === 'high' && 
             todo.dueDate && 
             !todo.completed &&
             new Date(todo.dueDate) > new Date() && 
             new Date(todo.dueDate) < new Date(Date.now() + 24 * 60 * 60 * 1000);
    },
    clearSearch() {
      this.searchQuery = '';
    },
    toggleTodoSelection(id) {
      const index = this.selectedTodos.indexOf(id);
      if (index === -1) {
        this.selectedTodos.push(id);
      } else {
        this.selectedTodos.splice(index, 1);
      }
    },
    batchComplete() {
      this.$emit('batch-complete', this.selectedTodos);
      this.selectedTodos = [];
    },
    batchDelete() {
      if (confirm(`确定要删除选中的 ${this.selectedTodos.length} 个任务吗？`)) {
        this.$emit('batch-delete', this.selectedTodos);
        this.selectedTodos = [];
      }
    },
    cancelSelection() {
      this.selectedTodos = [];
    },
    onDragStart(event, todoId) {
      this.dragTodoId = todoId;
      event.dataTransfer.effectAllowed = 'move';
    },
    onDragOver(event, todoId) {
      if (this.dragTodoId !== todoId) {
        event.preventDefault();
        event.dataTransfer.dropEffect = 'move';
      }
    },
    onDrop(event) {
      event.preventDefault();
      if (this.dragTodoId) {
        this.$emit('reorder-todos', this.dragTodoId, event);
        this.dragTodoId = null;
      }
    }
  }
}
</script>

<style scoped>
.todo-list {
  margin-bottom: 30px;
}

h2 {
  color: #34495e;
  margin-bottom: 15px;
  font-size: 1.5rem;
}

.filters {
  margin-bottom: 20px;
}

.filters button {
  background-color: #ecf0f1;
  color: #7f8c8d;
  border: none;
  padding: 8px 15px;
  margin-right: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.filters button.active,
.filters button:hover {
  background-color: #3498db;
  color: white;
}

.sort-options {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.sort-options label {
  margin-right: 10px;
  font-weight: normal;
}

.sort-options select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.search-box {
  position: relative;
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  padding: 10px 40px 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.search-input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 5px rgba(52, 152, 219, 0.3);
}

.clear-search {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #95a5a6;
}

.clear-search:hover {
  color: #7f8c8d;
}

.todos-container {
  list-style-type: none;
}

.todo-item {
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: box-shadow 0.3s;
  cursor: move;
}

.todo-item:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transform: translateY(-2px);
}

.todo-item:active {
  cursor: grabbing;
}

.todo-item:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.todo-content {
  flex: 1;
}

.todo-title {
  font-weight: bold;
  font-size: 1.1rem;
  margin-bottom: 5px;
}

.todo-description {
  margin-bottom: 10px;
  color: #7f8c8d;
}

.todo-meta {
  display: flex;
  gap: 15px;
  font-size: 0.9rem;
  color: #7f8c8d;
  margin-bottom: 10px;
}

.todo-category {
  background-color: #e8f4fc;
  padding: 2px 8px;
  border-radius: 4px;
}

.todo-priority {
  background-color: #fef9e7;
  padding: 2px 8px;
  border-radius: 4px;
}

.todo-due-date.high-priority {
  color: #e74c3c;
  font-weight: bold;
}

.todo-tags {
  display: flex;
  gap: 5px;
}

.tag {
  background-color: #ebf5fb;
  color: #3498db;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
}

.todo-actions {
  display: flex;
  gap: 10px;
}

.btn-complete,
.btn-edit,
.btn-delete {
  padding: 5px 10px;
  font-size: 0.9rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-complete {
  background-color: #2ecc71;
  color: white;
}

.btn-complete:hover {
  background-color: #27ae60;
}

.btn-complete.completed {
  background-color: #95a5a6;
}

.btn-edit {
  background-color: #f39c12;
  color: white;
}

.btn-edit:hover {
  background-color: #d35400;
}

.btn-delete {
  background-color: #e74c3c;
  color: white;
}

.btn-delete:hover {
  background-color: #c0392b;
}

.completed .todo-title {
  text-decoration: line-through;
  color: #95a5a6;
}

.batch-actions {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  border: 1px solid #dee2e6;
}

.btn-batch-complete,
.btn-batch-delete,
.btn-batch-cancel {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-batch-complete {
  background-color: #28a745;
  color: white;
}

.btn-batch-complete:hover {
  background-color: #218838;
}

.btn-batch-delete {
  background-color: #dc3545;
  color: white;
}

.btn-batch-delete:hover {
  background-color: #c82333;
}

.btn-batch-cancel {
  background-color: #6c757d;
  color: white;
}

.btn-batch-cancel:hover {
  background-color: #5a6268;
}

.todo-selection {
  margin-right: 15px;
  display: flex;
  align-items: center;
}

.todo-selection input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.todo-item.selected {
  background-color: #e3f2fd;
  border-color: #2196f3;
}

.empty-state {
  text-align: center;
  color: #95a5a6;
  font-style: italic;
  padding: 30px;
  border: 1px dashed #ddd;
  border-radius: 4px;
}
@media (max-width: 768px) {
  .todo-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .todo-content {
    width: 100%;
    margin-bottom: 15px;
  }
  
  .todo-meta {
    flex-wrap: wrap;
  }
  
  .todo-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .batch-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .batch-actions button {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .batch-actions button:last-child {
    margin-bottom: 0;
  }
}

@media (max-width: 480px) {
  .filters button {
    margin-bottom: 5px;
  }
  
  .search-input {
    padding: 8px 30px 8px 10px;
  }
  
  .todo-item {
    padding: 12px;
  }
}

/* 夜间模式样式 */
.dark-mode .todo-list {
  background-color: #2d2d2d;
  color: #e0e0e0;
}

.dark-mode .filters button {
  background-color: #424242;
  color: #e0e0e0;
  border-color: #555;
}

.dark-mode .filters button.active,
.dark-mode .filters button:hover {
  background-color: #1976d2;
}

.dark-mode .sort-options select,
.dark-mode .search-input {
  background-color: #424242;
  color: #e0e0e0;
  border-color: #555;
}

.dark-mode .todo-item {
  background-color: #333;
  border-color: #555;
}

.dark-mode .todo-item:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.3);
}

.dark-mode .todo-title {
  color: #e0e0e0;
}

.dark-mode .todo-description {
  color: #aaa;
}

.dark-mode .todo-meta {
  color: #aaa;
}

.dark-mode .todo-category {
  background-color: #1565c0;
  color: white;
}

.dark-mode .todo-priority {
  background-color: #f57f17;
  color: white;
}

.dark-mode .tag {
  background-color: #424242;
  color: #e0e0e0;
}

.dark-mode .btn-complete {
  background-color: #388e3c;
}

.dark-mode .btn-edit {
  background-color: #f57c00;
}

.dark-mode .btn-delete {
  background-color: #d32f2f;
}

.dark-mode .batch-actions {
  background-color: #424242;
  border-color: #555;
}

.dark-mode .empty-state {
  color: #aaa;
  border-color: #555;
}
</style>